﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Core;

namespace Framework
{
    public class SecurityService
    {
        /// <summary>
        /// 加载用户权限集合
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        //private Dictionary<string, List<OrganizationScope>> GetUserRoles(string userName)
        //{
        //    //List<UserRole> userRoleList = new UserRoleDataAccess().GetUserRoles(userName);
        //    //Dictionary<string, List<OrganizationScope>> result = new Dictionary<string, List<OrganizationScope>>();
        //    //foreach (UserRole uRole in userRoleList)
        //    //{
        //    //    string role = uRole.RoleID;
        //    //    string scopeId = uRole.OrgID;
        //    //    OrgTree tree = SecurityCache.GetInstance().OrganizationTree;// OrgTreeProvider.GetOrganizationTree();
        //    //    OrgTreeNode node = tree.SelectNodeById(scopeId);
        //    //    if (node == null || string.IsNullOrEmpty(role) || string.IsNullOrEmpty(scopeId))
        //    //    {
        //    //        continue;
        //    //    }
        //    //    string scope = node.FullName;
        //    //    if (!result.ContainsKey(role))
        //    //    {
        //    //        List<OrganizationScope> organizationScopeList = new List<OrganizationScope>();
        //    //        organizationScopeList.Add(new OrganizationScope(scope));
        //    //        result.Add(role, organizationScopeList);
        //    //    }
        //    //    else
        //    //    {
        //    //        result[role].Add(new OrganizationScope(scope));
        //    //    }
        //    //}
        //    //return result;
        //    return null;
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public User UserLogin(string userName, string passWord)
        {
            UserBll bll = new UserBll();
            if (bll.VerifyPassword(userName, passWord))
            {
                return bll.LoadUserBaseInfo(userName);
            }
            return null;
        }

        public bool ValidateControl(User user, string pageName, string controlID)
        {
            foreach (RoleInfo role in user.Roles)
            {
                foreach (RuleInfo rule in role.RuleInfos)
                {
                    if (rule.RulePages.Where(m => m.PageName.Equals(pageName, StringComparison.CurrentCultureIgnoreCase) &&
                        m.ControlName.Equals(controlID, StringComparison.CurrentCultureIgnoreCase)).Count() > 0)
                        return true;
                }
            }
            return false;
        }
    }
}
